package com.sui.bigdata.sml.model.model;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import com.sui.bigdata.sml.model.util.Utils;
import lombok.Data;
import lombok.NonNull;
import lombok.experimental.Accessors;

import java.util.HashMap;
import java.util.Map;

/**
 * @author songhaicheng
 * @date 2019/12/2 14:08
 * @description
 * @reviewer
 */
@Data
@Accessors(chain = true)
public class InferenceRequest {
    /**
     * 业务ID
     */
    private String busId;
    /**
     * 模型特征（有多物品特征时，此处作为公共特征）
     */
    private Map<String, Object> features;
    /**
     * 多物品特征
     * key：物品ID，value：物品特征
     */
    private Map<String, Map<String, Object>> multiFeatures;
    /**
     * 结果top
     */
    private int top;
    /**
     * 请求跟踪ID
     */
    @NonNull
    private String traceId;
    /**
     * 拼装 {@link #features} 和 ${@link #multiFeatures} 的究极无敌 feature
     */
    @JSONField(serialize = false)
    private Map<String, Map<String, Object>> totalFeatures;

    public Map<String, Map<String, Object>> getTotalFeatures() {
        if (totalFeatures == null) {
            if (Utils.isMapEmpty(features) && Utils.isMapEmpty(multiFeatures)) {
                return null;
            }
            if (!Utils.isMapEmpty(multiFeatures)) {
                // 初始化究极 totalFeatures，先按照多候选集的 key 把公共特征放进去，再把具体每个候选集的特征放进去
                // 如果公共特征与候选集里的特征有重复，以候选集里面的为准
                totalFeatures = new HashMap<>(multiFeatures.size());
                multiFeatures.keySet().forEach(key -> {
                    if (features != null) {
                        totalFeatures.put(key, new HashMap<>(features));
                    } else {
                        totalFeatures.put(key, new HashMap<>());
                    }
                });
                totalFeatures.forEach((key, value) -> value.putAll(multiFeatures.get(key)));
            } else {
                totalFeatures = new HashMap<>(1);
                totalFeatures.put("单组特征", features);
            }
        }
        return totalFeatures;
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }

}
